package com.xxl.job.admin.core.alarm.impl;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.open.dingtalk.DingtalkRobotClient;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DateUtil;

/**
 * 
 * 描述：钉钉消息通知
 * 
 * @author qizai
 * @version: 0.0.1 2021年5月7日-下午1:57:37
 *
 */
@Component
public class DingtalkJobAlarm implements JobAlarm {
	private static Logger logger = LoggerFactory.getLogger(DingtalkJobAlarm.class);

	public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
		boolean alarmResult = true;
		// access_token@secret;多个使用冒号分隔
		if (info != null && info.getAlarmDingtalk() != null && info.getAlarmDingtalk().trim().length() > 0) {
			String alarmContent = "执行日志ID：" + jobLog.getId() + " \n\n 执行时间：" + DateUtil.formatDateTime(new Date());
			if (jobLog.getTriggerCode() != ReturnT.SUCCESS_CODE) {
				alarmContent += "\n\n " + jobLog.getTriggerMsg().replaceAll("<br>", "\n\n");
			}
			if (jobLog.getHandleCode() > 0 && jobLog.getHandleCode() != ReturnT.SUCCESS_CODE) {
				alarmContent += "\n\n 调度结果：" + jobLog.getHandleMsg().replaceAll("<br>", "\n\n");
			}
			XxlJobGroup group = XxlJobAdminConfig.getAdminConfig().getXxlJobGroupDao()
					.load(Integer.valueOf(info.getJobGroup()));
			String title = I18nUtil.getString("jobconf_monitor");
			String content = MessageFormat.format("执行器：{0} \n\n  任务ID：{1} \n\n 任务描述：{2} \n\n {3}",
					group != null ? group.getTitle() : "null", info.getId(), info.getJobDesc(), alarmContent);

			Set<String> dingtalkSet = new HashSet<String>(Arrays.asList(info.getAlarmDingtalk().split(";")));
			for (String dingtalk : dingtalkSet) {
				try {
					String[] keys = dingtalk.split("@");
					if (keys.length > 1) {
						DingtalkRobotClient.sendMarkdown(keys[0], keys[1], title, content);
					}
				} catch (Exception e) {
					logger.error(">>>>>>>>>>> xxl-job, job fail alarm dingtalk send error, JobLogId:{}", jobLog.getId(),
							e);
					alarmResult = false;
				}
			}
		}
		return alarmResult;
	}

}
